﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xc.Core.Tools;

namespace ExamSelfTouch.Tools
{
    public sealed class HttpBase
    {
        private static readonly HttpClient client = new HttpClient();

        private HttpBase() { }

        static HttpBase() { }

        private static HttpClient GetHttpBase()
        {
            if (client == null || client.BaseAddress == null)
            {
                client.BaseAddress = new Uri(ConfigurationManager.AppSettings["QuestionAddress"]);
                // Add an Accept header for JSON format.
                // 为JSON格式添加一个Accept报头
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
            }
            return client;
        }

        /// <summary>
        /// 异步Get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<T> GetAsync<T>(string url) where T : class
        {
            HttpResponseMessage response = await GetHttpBase().GetAsync(url);  // Blocking call（阻塞调用）! 
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<T>();
                return data;
            }
            else
            {
                LogTool.WriteErrorLog(string.Format("异步Get请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// 同步Get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static T Get<T>(string url) where T : class
        {
            HttpResponseMessage response = client.GetAsync(url).Result;  // Blocking call（阻塞调用）! 
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsAsync<T>().Result;
                return data;
            }
            else
            {
                LogTool.WriteErrorLog(string.Format("Get请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// 异步Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static async Task<Boolean> PostAsJsonAsync(string url, object entity)
        {
            HttpResponseMessage response = await client.PostAsJsonAsync(url, entity);
            if (response.IsSuccessStatusCode)
                return true;
            else
            {
                LogHelper.WriteLog(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return false;
            }
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Boolean PostAsJson(string url, object entity)
        {
            HttpResponseMessage response = client.PostAsJsonAsync(url, entity).Result;
            if (response.IsSuccessStatusCode)
                return true;
            else
            {
                LogHelper.WriteLog(string.Format("Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return false;
            }
        }

        /// <summary>
        /// 异步Post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static async Task<T> PostAsJsonAsync<T>(string url, object entity) where T : class
        {
            HttpResponseMessage response = await client.PostAsJsonAsync(url, entity);
            if (response.IsSuccessStatusCode)
            {
                var data = await response.Content.ReadAsAsync<T>();
                return data;
            }
            else
            {
                LogTool.WriteErrorLog(string.Format("异步Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static T PostAsJson<T>(string url, object entity) where T : class
        {
            HttpResponseMessage response = client.PostAsJsonAsync(url, entity).Result;
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsAsync<T>().Result;
                return data;
            }
            else
            {
                LogHelper.WriteLog(string.Format("Post请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// 异步删除请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<Boolean> DeleteAsync(string url)
        {
            HttpResponseMessage response = await client.DeleteAsync(url);
            if (response.IsSuccessStatusCode)
                return true;
            else
            {
                LogHelper.WriteLog(string.Format("异步Delete请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return false;
            }
        }

        /// <summary>
        /// 删除请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Boolean Delete(string url)
        {
            HttpResponseMessage response = client.DeleteAsync(url).Result;
            if (response.IsSuccessStatusCode)
                return true;
            else
            {
                LogHelper.WriteLog(string.Format("Delete请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return false;
            }
        }

        /// <summary>
        /// 异步删除请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<T> DeleteAsync<T>(string url) where T : class
        {
            HttpResponseMessage response = await client.DeleteAsync(url);
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsAsync<T>().Result;
                return data;
            }
            else
            {
                LogHelper.WriteLog(string.Format("异步Delete请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }

        /// <summary>
        /// 删除请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static T Delete<T>(string url) where T : class
        {
            HttpResponseMessage response = client.DeleteAsync(url).Result;
            if (response.IsSuccessStatusCode)
            {
                var data = response.Content.ReadAsAsync<T>().Result;
                return data;
            }
            else
            {
                LogHelper.WriteLog(string.Format("Delete请求，url:{0}，调用失败，状态：{1},原因：{2}", url, response.StatusCode, response.ReasonPhrase));
                return null;
            }
        }
    }
}
